package com.example.thymeleaf.controller;

import com.example.thymeleaf.common.TokenUtils;
import com.example.thymeleaf.entity.CityEntity;
import com.example.thymeleaf.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @ClassName UserController
 * @Author fuzhixuan
 * @Date 2022/1/20 11:08
 */
@Controller
public class CityController {
    @Autowired
    private CityService cityService;

    @GetMapping(value = "/getAll")
    @ResponseBody
    public String getAll(Model model, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (!TokenUtils.verify(token)) {
            return "error";
        } else {
            return "success";
        }
    }

    @GetMapping(value = "/index")
    public String index(Model model) {
        model.addAttribute("cityList", cityService.getAll());
        model.addAttribute("title", "所有城市如下：");
        model.addAttribute("curDate", new Date());
        return "index";
    }

    @GetMapping(value = "/error")
    public String error(Model model) {
        model.addAttribute("errorMsg", "token错误");
        return "error";
    }

    @GetMapping(value = "/getOneCity")
    public String getOneCity(Model model, @RequestParam Integer id) {
        model.addAttribute("city", cityService.getCityById(id));
        return "update_city";
    }

    @PostMapping(value = "/updateCity")
    @ResponseBody
    public String updateCity(@RequestBody CityEntity cityEntity) {
        cityService.updateCity(cityEntity);
        return "ok";
    }
}
